package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.constant.GlobalConstant;
import com.heima.common.exception.CustomException;
import com.heima.model.admin.dtos.AdLoginDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dots.LoginDto;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    @Override
    public ResponseResult login(AdLoginDto dto) {
        if(dto==null)
        {
            throw new CustomException(AppHttpCodeEnum.PARAMS_NOT_NULL);
        }
        if (dto.getName()==null)
        {
            throw new CustomException(AppHttpCodeEnum.ACCOUNT_NOT_NULL);
        }
        if (dto.getPassword()==null)
        {
            throw new CustomException(AppHttpCodeEnum.PASSWORD_NOT_NULL);
        }
        AdUser user = this.getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
        if (user==null)
        {
            throw new CustomException(AppHttpCodeEnum.USER_NOT_EXIST);
        }
        if (!user.getPassword().equals(DigestUtils.md5DigestAsHex((dto.getPassword()+user.getSalt()).getBytes())))
        {
            throw new CustomException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        String token = AppJwtUtil.getToken(user.getId().longValue());
        Map<String,Object> map=new HashMap<>();
        user.setPassword(null);
        user.setSalt(null);
        map.put(GlobalConstant.USER_TAG,user);
        map.put(GlobalConstant.TOKEN_TAG,token);
        return ResponseResult.okResult(map);
    }
}
